/**
 *
 * @param {Object} workBook 工作薄
 * @param {Object} workSheet 工作表
 * @param {Object} cell 单元格
 * 标记，引用单元格时所使用的地址格式（如：A1、C7）
 */

import { saveAs } from "file-saver";
import * as XLSX from 'xlsx'

function dateNum(v, date1904) {
  if (date1904) v += 1462;
  let epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheetFromArrayOfArrays(data) {
  let ws = {};
  let range = {
    s: {
      c: 10000000,
      r: 10000000
    },
    e: {
      c: 0,
      r: 0
    }
  };
  for (let R = 0; R !== data.length; ++R) {
    for (let C = 0; C !== data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      let cell = {
        v: data[R][C],
      };
      if (cell.v == null) continue;
      let cellRef = XLSX.utils.encode_cell({ c: C, r: R });

      if (typeof cell.v === "number") cell.t = "n";
      else if (typeof cell.v === "boolean") cell.t = "b";
      else if (cell.v instanceof Date) {
        cell.t = "n";
        cell.z = XLSX.SSF._table[14];
        cell.v = dateNum(cell.v);
      } else cell.t = "s";

      ws[cellRef] = cell;
    }
  }
  if (range.s.c < 10000000) ws["!ref"] = XLSX.utils.encode_range(range);
  return ws;
}

function workBook() {
  if (!(this instanceof workBook)) return new workBook();
  this.SheetNames = [];
  this.Sheets = {};
}

function s2ab(s) {
  let buf = new ArrayBuffer(s.length);
  let view = new Uint8Array(buf);
  for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
  return buf;
}

/**
 *
 * @param {Array} multiHeader  多行表头,三维数组,因为每一行都是一个数组
 * @param {Array} header  表头
 * @param {Array} data  数据
 * @param {String} fileName  文件名
 * @param {Array} merges  合并单元格
 * @param {Boolean} autoWidth  是否设置单元格宽度
 * @param {String} bookType  要生成的文件类型
 */
export function exportJsonToExcel({
  multiHeader = [],
  header,
  data,
  fileName,
  sheetName,
  merges = [],
  autoWidth = true,
  bookType = "xlsx"
} = {}) {
  fileName = fileName || "excel-list";

  for (let i in header) {
    data[i] = [...data[i]];
    data[i].unshift(header[i]);
  }

  for (let j in data) {
    if (multiHeader[j]) {
      for (let i = multiHeader[j].length - 1; i > -1; i--) {
        data[j].unshift(multiHeader[j][i]);
      }
    }
  }
  let wb = new workBook();

  let ws = [];
  for (let i in data) {
    ws.push(sheetFromArrayOfArrays(data[i]));
  }

  if (merges.length > 0) {
    for (let i in ws) {
      if (!wa[i]["!merges"]) {
        ws[i]["!merges"] = [];
      }
      if (merges[i]) {
        merges[i].forEach((item) => {
          ws[i]["!merges"].push(XLSX.utils.decode_range(item));
        });
      }
    }
  }

  if (autoWidth) {
    const colWidth = data.map((row) =>
      row.map((val) => {
        if (val == null) {
          return { wch: 10 };
        } else if (val.toString().charCodeAt(0) > 255) {
          return {
            wch: val.toString().length * 2
          };
        } else {
          return {
            wch: val.toString().length
          }
        }
      })
    );
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j] && result[j]["wch"] < colWidth[i][j]["wch"]) {
          result[j]["wch"] = colWidth[i][j]["wch"];
        }
      }
    }
    for (let i in ws) {
      ws[i]["!cols"] = result;
    }
  }

  for (let i in sheetName) {
    wb.SheetNames.push(sheetName[i]);
    wb.Sheets[sheetName[i]] = ws[i];
  }

  let wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: "binary"
  })
  saveAs(new Blob([s2ab(wbout)], { type: "application/vnd.ms-excel" }), `${fileName}.${bookType}`);
}//https://blog.csdn.net/langwang_100/article/details/134597236?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7Ebaidujs_baidulandingword%7ECtr-3-134597236-blog-144502497.235%5Ev43%5Epc_blog_bottom_relevance_base7&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7Ebaidujs_baidulandingword%7ECtr-3-134597236-blog-144502497.235%5Ev43%5Epc_blog_bottom_relevance_base7&utm_relevant_index=6